﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HPT.Utilities;

namespace HPT
{
    [Serializable]
    public class SPItem
    {
        public SPItem()
        {
            CreatedBy = new UserItem();
            UpdatedBy = new UserItem();
        }
        public SPItem(SPListItem item)
        {
            Id = item.ID;
            Title = item.Title;

            Updated = OConvert.ToDateTime(item[SPBuiltInFieldId.Modified]);

            var modifiedBy = OConvert.ToSPFieldUserValue(item[SPBuiltInFieldId.Editor]);
            UpdatedBy = new UserItem(modifiedBy.User);

            Created = OConvert.ToDateTime(item[SPBuiltInFieldId.Created]);

            var createdBy = OConvert.ToSPFieldUserValue(item[SPBuiltInFieldId.Author]);
            CreatedBy = new UserItem(createdBy.User);
        }

        public SPItem(SPFieldLookupValue lookup)
        {
            if (lookup == null) return;
            Id = lookup.LookupId;
            Title = lookup.LookupValue;
        }

        public int Id { get; set; }
        public string Title { get; set; }

        public DateTime? Created
        {
            get;
            set;
        }

        public DateTime? Updated
        {
            get;
            set;
        }

        public UserItem CreatedBy
        {
            get;
            set;
        }

        public UserItem UpdatedBy
        {
            get;
            set;
        }
        public SPFieldLookupValue ToLookupValue()
        {
            return new SPFieldLookupValue(Id, Title);
        }


        protected static SPFieldLookupValueCollection ToLookupValueCollection<T>(List<T> list)
        {
            var result = new SPFieldLookupValueCollection();
            foreach (var item in list)
                result.Add((item as SPItem).ToLookupValue());
            return result;
        }
    }
}
